package com.huxiu.yd;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.responses.ProfileResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendAuth.Req;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/7/28:上午11:21.
 */
public class LogInActivity extends AuthenticatorActivity implements OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.username_edit)
    EditText usernameEdit;

    @InjectView(R.id.password_edit)
    EditText passwordEdit;

    @InjectView(R.id.forget_password)
    TextView forgetPassword;

    @InjectView(R.id.weibo_log_in)
    ImageView weiboLogIn;

    @InjectView(R.id.qq_log_in)
    ImageView qqLogIn;

    @InjectView(R.id.weixin_log_in)
    ImageView weixinLogIn;

    @InjectView(R.id.huxiu_log_in)
    ImageView huxiuLogIn;

    @InjectView(R.id.oauth_log_in_layout)
    LinearLayout oauthLogInLayout;

    @InjectView(R.id.oauth_hint)
    TextView oauthHint;

    @InjectView(R.id.log_in_button)
    Button logInButton;

    private static final boolean DEBUG = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        title.setText(R.string.log_in);
        rightImage.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(R.string.register);
        rightText.setTextColor(getResources().getColor(R.color.button_green));
        rightText.setOnClickListener(this);
        forgetPassword.setOnClickListener(this);
        huxiuLogIn.setOnClickListener(this);
        weiboLogIn.setOnClickListener(this);
        weixinLogIn.setOnClickListener(this);
        qqLogIn.setOnClickListener(this);
        logInButton.setOnClickListener(this);
        if (BuildConfig.DEBUG) {
            usernameEdit.setText("13910028267");
            passwordEdit.setText("123456");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_text:
                startActivityForResult(new Intent(this, RegisterActivity.class),
                        REQUEST_CODE_BIND_OR_REGISTER);
                break;
            case R.id.log_in_button:
                if (inputValid()) {
                    logIn("local");
                }
                break;
            case R.id.huxiu_log_in:
                startActivity(new Intent(this, HuxiuLogInActivity.class));
                break;
            case R.id.qq_log_in:
                if (mTencent != null) {
                    mTencent.login(this, "all", this);
                } else {
                    Utils.showToast(R.string.qq_log_in_failed);
                }
                break;
            case R.id.weibo_log_in:
                mSsoHandler.authorize(this);
                break;
            case R.id.weixin_log_in:
                if (mWechatApi.isWXAppInstalled()) {
                    SendAuth.Req req = new Req();
                    req.scope = "snsapi_userinfo";
                    mWechatApi.sendReq(req);
                } else {
                    Utils.showToast(R.string.weixin_not_installed);
                }
                break;
            case R.id.forget_password:
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra("forget_password", true);
                startActivity(intent);
                break;
        }
    }

    private boolean inputValid() {
        if (TextUtils.isEmpty(usernameEdit.getText().toString())) {
            Utils.showToast(R.string.invalid_username);
            return false;
        }
        if (TextUtils.isEmpty(passwordEdit.getText().toString())) {
            Utils.showToast(R.string.invalid_password);
            return false;
        }
        return true;
    }

    protected void logIn(String type) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("username", usernameEdit.getText().toString());
        params.put("password", Utils.getEncryptedPassword(passwordEdit.getText().toString()));
        LogUtils.d("password is " + Utils.getEncryptedPassword(passwordEdit.getText().toString()));
        params.put("act", "login");
        params.put("login_type", type);
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Method.POST,
                ProfileResponse.class, false, params, new Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    Settings.saveProfile(response.data.toString());
                    Global.setUser(response.data);
                    Utils.showToast(R.string.log_in_success);
                    LocalBroadcastManager.getInstance(App.getInstance()).sendBroadcast(new Intent(
                            Constants.INTENT_USER_LOGGED_IN));
                    setResult(RESULT_OK);
                    finish();
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
        showProgress();
    }

    private static final String TAG = LogInActivity.class.getCanonicalName();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

}